import { Switch } from '@headlessui/react'
import classNames from 'classnames'
import { ReactNode, useEffect, useState } from 'react'
import styles from './Switcher.module.scss'

interface SwitcherProps {
  className: string
  isChecked: boolean
  onChange: (checked: boolean) => void
  renderOff?: ReactNode
  renderOn?: ReactNode
}

export const Switcher = ({
  className,
  isChecked,
  onChange,
  renderOff,
  renderOn,
}: SwitcherProps) => {
  const [checked, setChecked] = useState(false)
  const toggle = () => {
    setChecked((prev) => !prev)
    onChange(checked)
  }
  useEffect(() => {
    setChecked(isChecked)
  }, [])

  return (
    <Switch
      checked={checked}
      className={classNames(styles.custom, { [styles.enabled]: checked }, className)}
      onChange={toggle}
    >
      <div className={styles['icon-wrapper']}>
        <div className={classNames(styles.icon, { [styles['icon-white']]: !checked })}>
          {renderOff}
        </div>
        <div className={classNames(styles.icon, { [styles['icon-white']]: checked })}>
          {renderOn}
        </div>
      </div>
    </Switch>
  )
}
